package com.zksk.admin.service.market.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksk.admin.domain.market.dto.SaleRecordDto;
import com.zksk.admin.domain.market.vo.SaleCardVo;
import com.zksk.admin.mapper.market.SaleRecordDao;
import com.zksk.admin.service.market.SaleRecordService;
import com.zksk.mbg.admin.domain.SaleRecord;
import com.zksk.mbg.admin.mapper.SaleRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * <p>
 * 营销记录 服务实现类
 * </p>
 *
 * @author Zksk Acmen
 * @since 2022-12-14
 */
@Service
public class SaleRecordServiceImpl extends ServiceImpl<SaleRecordMapper, SaleRecord> implements SaleRecordService {

    @Autowired
    private SaleRecordMapper saleRecordMapper;

    @Autowired
    private SaleRecordDao saleRecordDao;


    @Override
    public SaleRecord saveSaleRecord(SaleRecord saleRecord) {
        // 如果已经存在该sale卡片  查询出来 并更新
        // 保存营销记录时 对与营销卡片的处理
        if (saleRecord.getId() != null && saleRecord.getId() > 0) {
            saleRecordMapper.updateById(saleRecord);
        }else{
            saleRecordMapper.insert(saleRecord);
        }
        return saleRecord;
    }

    @Override
    public List<SaleCardVo> cardList(Long memberId) {

        List<SaleRecordDto> list = saleRecordDao.selectSaleRecordList(memberId);

        // 根据产品枚举id jinxing 分组
        TreeMap<Long, List<SaleRecordDto>> groupTree =
                list.stream().collect(Collectors.groupingBy(SaleRecordDto::getEnumProductId, TreeMap::new, Collectors.toList()));
        List<SaleCardVo> saleCardVos = new ArrayList<>();
        groupTree.forEach((key,item) -> {
            SaleCardVo vo = new SaleCardVo();
            vo.setProductEnumId(key.toString());
            vo.setProductEnumName(item.get(0).getEnumProductName());
            vo.setRecordCount(item.size());
            vo.setProductStatus(item.size() > 0 ? 1 : 0);
            vo.setSaleRecordList(item); // 该枚举产品对应的营销记录
            vo.setIfMarket(0);
            vo.setLevel(item.get(0).getLevel());
            saleCardVos.add(vo);
        });

        return saleCardVos;
    }
}
